<template>
  <!-- 商品卡片 -->
  <div class="item-list">
    <div class="lists" v-for="(item,index) in list" :key="index">
      <figure>
        <!-- 商品图片 -->
        <img :src="item.mainPic" @click="toDetails(item)" />
        <!-- 商品title -->
        <p @click="toDetails(item.id)">{{item.title}}</p>
        <div class="goods-price" @click="toDetails(item)">
          <!-- 商品折后价 -->
          <p>
            <b>券后:{{item.actualPrice}}</b>
          </p>
          <!-- 商品原价 -->
          <p>
            <small>
              <s>原{{item.originalPrice}}</s>
            </small>
          </p>
        </div>
        <div class="goods-cart">
          <p>
            <small>销量{{item.monthSales}}</small>
          </p>
          <p class="iconfont icon-jiagouwuche" @click="tocart(item)"></p>
        </div>
      </figure>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    list: Array
  },
  data() {
    return {
      cart: [] //临时存储
    };
  },
  mounted() {
    //初始化购物车
    let cart = localStorage.cart;
    if (cart != undefined) {
      this.cart = JSON.parse(cart);
    }
  },
  methods: {
    tocart(item) {
      //1.判断商品重复添加
      let isFirst = true; //是否为第一次添加，默认为true
      this.cart.map(i => {
        if (i.goods.id == item.id) {
          i.num++;
          isFirst = false;
          return;
        }
      });

      //2.商品初次添加购物车
      if (isFirst) {
        let cart = {
          goods: item,
          num: 1
        };
        this.cart.push(cart);
      }

      //3.本地同步
      localStorage.cart = JSON.stringify(this.cart);
    },
    toDetails(item) {
      this.$router.push({
        path: "/details",
        query: {
          id: item.id
        }
      });
    }
  }
};
</script>

<style scoped>
.item-list {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.lists {
  width: 45%;
}

.lists figure {
  width: 100%;
}

.lists figure img {
  width: 100%;
}

.lists figure p {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  color: #646566;
}

.goods-price {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.goods-price p:nth-child(2) {
  width: 30%;
}
.goods-cart {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.goods-cart p:nth-child(2) {
  width: 30%;
}
</style>
